package com.kyxx.topics.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.MyCommonTitle;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cz.msebera.android.httpclient.Header;

public class UserLoginActivity extends Activity implements View.OnClickListener, Callback, PlatformActionListener {

    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;
    private MyCommonTitle myCommonTitle;
    private RequestParams params;
    private EditText ed_username, ed_password;
    private TextView btn_login, btn_register, btn_forgetPwd;
    private String userMobile, password, token;
    private TextView btn_qq, btn_wx;
    private int thirdLogin = 0, type, i, j;
    private Handler mHandler;
    private String openId, nickname, avatar;
    private JSONObject jsonObject, jsonObject1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        mHandler = new Handler(this.getMainLooper(), this);
        ShareSDK.initSDK(this);

        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        myCommonTitle = (MyCommonTitle) findViewById(R.id.aci_myTitle);
        myCommonTitle.setTitle("登录");
        ed_username = (EditText) findViewById(R.id.ed_username);// 用户名
        ed_password = (EditText) findViewById(R.id.ed_password);// 密码
        btn_login = (TextView) findViewById(R.id.btn_login);// 登录
        btn_register = (TextView) findViewById(R.id.btn_register);// 注册
        btn_forgetPwd = (TextView) findViewById(R.id.btn_forget_pwd);// 忘记密码

        btn_qq = (TextView) findViewById(R.id.btn_QQ);// QQ登录
        btn_wx = (TextView) findViewById(R.id.btn_WX);// 威信登录

        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        btn_forgetPwd.setOnClickListener(this);
        btn_qq.setOnClickListener(this);
        btn_wx.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        userMobile = ed_username.getText().toString().trim();
        password = ed_password.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_register:// 跳转注册界面
                startActivity(new Intent(UserLoginActivity.this, UserRegisterActivity.class).putExtra("type", "register"));
                finish();
                break;
            case R.id.btn_forget_pwd:// 跳转忘记密码界面
                startActivity(new Intent(UserLoginActivity.this, UserRegisterActivity.class).putExtra("type", "forget_pwd"));
                finish();
                break;
            case R.id.btn_login:
                if (StringUtil.isEmpty(userMobile)) {
                    Tools.toast(UserLoginActivity.this, "手机号码不能为空！");
                    return;
                }
                if (StringUtil.isEmpty(password)) {
                    Tools.toast(UserLoginActivity.this, "密码不能为空！");
                    return;
                }
                submitData();
                break;
            case R.id.btn_QQ:
                type = 1;
                thirdLogin = 1;
                Platform qq = ShareSDK.getPlatform(this, QQ.NAME);
                qq.setPlatformActionListener(this);
                qq.SSOSetting(false);
                qq.authorize();
                break;
            case R.id.btn_WX:
                type = 2;
                thirdLogin = 1;
                Platform weixin = ShareSDK.getPlatform(this, Wechat.NAME);
                weixin.setPlatformActionListener(this);
                weixin.SSOSetting(true);
                weixin.authorize();
                break;
            default:
                break;
        }
    }

    /**
     * 正常注册后登录 提交信息，调用登录接口 "id": "15", "username": "", "pwd":
     * "e3ceb5881a0a1fdaad01296d7554868d", "mobile": "18660992783", "addtime":
     * "1463471681", "nickname": "", "avatar": ""
     */
    private void submitData() {
//        jsonObject = new JSONObject();
//        jsonObject.put("Password", password);
//        jsonObject.put("LoginName", userMobile);
//        jsonObject.put("Mode", type);
//        StringEntity s = null;
//        try {
//            s = new StringEntity(jsonObject.toString(), "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        RequestParams params = new RequestParams();
        params.put("Password", password);
        params.put("LoginName", userMobile);
        RestClient.post(UrlUtils.LOGINFORPSW, params, UserLoginActivity.this, new ResponseListener(UserLoginActivity.this,true) {

            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject result) {

            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                super.failed(arg0, arg1, result);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (thirdLogin == 1) {
//            MyRequestDailog.showDialog(this, "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MyRequestDailog.closeDialog();
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Message msg = new Message();
        msg.what = MSG_AUTH_COMPLETE;
        msg.obj = platform;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        mHandler.sendEmptyMessage(MSG_AUTH_ERROR);
    }

    @Override
    public void onCancel(Platform platform, int action) {
        mHandler.sendEmptyMessage(MSG_AUTH_CANCEL);
    }

    @Override
    public boolean handleMessage(Message msg) {
        thirdLogin = 0;
        switch (msg.what) {
            case MSG_AUTH_CANCEL: {
                // 取消授权
//                MyRequestDailog.closeDialog();
                Tools.toast(this, "取消登录");
            }
            break;
            case MSG_AUTH_ERROR: {
                // 授权失败
//                MyRequestDailog.closeDialog();
                Tools.toast(this, "登录失败");
            }
            break;
            case MSG_AUTH_COMPLETE: {
                // 授权成功
//                Tools.toast(this, "登录成功");
                Platform platform = (Platform) msg.obj;
                // String icon = platform.getDb().getUserIcon();
                openId = platform.getDb().getUserId();
                nickname = platform.getDb().getUserName();// AE826801AB2F3F1BE28519C3DD44BE07
                avatar = platform.getDb().getUserIcon();
                BaseApp.getModel().setNickname(nickname);
                String gdg = BaseApp.getModel().getNickname();
                BaseApp.getModel().setAvatar(avatar);
                String aa = BaseApp.getModel().getAvatar();
                // String gender = platform.getDb().getUserGender();

                threeLogin(type);// 第三方登录
            }
            break;
        }
        return false;
    }

    /**
     * 第三方登陆,如果返回201未注册,先注册,注册成功后再登录
     * 登录成功后返回用户信息{"data":{"addtime":"1465699131","guid":
     * "A994A589C315C7CF44DB9C60D7C3AB1E","id":"47","nickname":"咖啡正浓",
     * "pwd":"11762fc9f747003d488defc5b050eabd","username":
     * "781465699131"},"status":200}
     */
    private void threeLogin(final int type) {
//        jsonObject = new JSONObject();
//        jsonObject.put("Password", "");
//        jsonObject.put("LoginName", userid);
//        jsonObject.put("Mode", type);
//        StringEntity s = null;
//        try {
//            s = new StringEntity(jsonObject.toString(), "utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        RequestParams params = new RequestParams();
        params.put("openid", openId);
        if (type == 1) {
            params.put("type", "oauth_qq_id");
        } else if (type == 2) {
            params.put("type", "oauth_wx_id");
        }
        RestClient.post(UrlUtils.THREELOGIN, params, UserLoginActivity.this, new ResponseListener(UserLoginActivity.this,true) {


            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject result) {

            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject result) {
                super.failed(arg0, arg1, result);
            }
        });
    }

}
